﻿using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFWebControl;

namespace AutoCreateLink
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window, INotifyPropertyChanged
    {
        string m_sUserName = "";
        string m_sPass = "sky031087";
        public MainWindow()
        {
            InitializeComponent();

            _listLinks = new ObservableCollection<LinkBuckItem>();
            DataContext = this;

        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }


        ObservableCollection<LinkBuckItem> _listLinks;
        public ObservableCollection<LinkBuckItem> ListLinks
        {
            get
            {
                return _listLinks;
            }
            set
            {
                if (_listLinks != value)
                {
                    _listLinks = value;
                    OnPropertyChanged("ListLinks");
                }
            }
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //If You Want to define a defualt URI then you can define like below...
                wb.Source = new Uri("https://www.linkbucks.com/");              
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void onLogin()
        {
            var doc = (mshtml.HTMLDocument)wb.Document;

            if (doc != null)
            {
                mshtml.HTMLInputElement userName = doc.getElementById("ctl00_LeftMenuBar_ctl00_Username") as mshtml.HTMLInputElement;
                mshtml.HTMLInputElement password = doc.getElementById("ctl00_LeftMenuBar_ctl00_Password") as mshtml.HTMLInputElement;
                //ctl00_LeftMenuBar_ctl00_LoginImgBtn
                mshtml.HTMLInputElement loginBtn = doc.getElementById("ctl00_LeftMenuBar_ctl00_LoginImgBtn") as mshtml.HTMLInputElement;
                if (userName != null && password != null && loginBtn != null)
                {
                    userName.value = "thelightsky";
                    password.value = m_sPass;
                    password.focus();

                    loginBtn.click();
                }
            }
            
        }

        private DateTime startTime;
        private void delay2second(Object sender, DoWorkEventArgs e)
        {
            while (true)
            {

                TimeSpan time = DateTime.Now - startTime;

                if (time.Seconds > 2)
                {
                    break;
                }

            }
        }

        private void startThreadCreateLink()
        {
            startTime = DateTime.Now;
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += delay2second;
            thread.RunWorkerCompleted += finishLogin;
            thread.WorkerReportsProgress = true;
            thread.WorkerSupportsCancellation = true;
            thread.RunWorkerAsync(); 
        }



        private void finishLogin(Object sender, RunWorkerCompletedEventArgs e)
        {
            onCreateLink();
        }

        private bool m_bStartCreate = false;
        private void onCreateLink()
        {
            //https://www.linkbucks.com/CreateLinks/Single/

            try
            {
                //If You Want to define a defualt URI then you can define like below...
                wb.Source = new Uri("https://www.linkbucks.com/CreateLinks/Single/");

                //Otherwise for blank you can set it as like below...
                //MyWebBrowser.Source = new Uri("about:blank");
                m_bStartCreate = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private string m_sCurrentLinkbuck;
       


        private void delay3second(Object sender, DoWorkEventArgs e)
        {
            while (true)
            {

                TimeSpan time = DateTime.Now - startTime;

                if (time.Seconds > 3)
                {
                    break;
                }

            }
        }

        private void waitvalue()
        {
            startTime = DateTime.Now;
            BackgroundWorker thread = new BackgroundWorker();
            thread.DoWork += delay3second;
            thread.RunWorkerCompleted += finishGenerate;
            thread.WorkerReportsProgress = true;
            thread.WorkerSupportsCancellation = true;
            thread.RunWorkerAsync();
        }



        private void finishGenerate(Object sender, RunWorkerCompletedEventArgs e)
        {
            var doc = (mshtml.HTMLDocument)wb.Document;

            if (doc != null)
            {
                mshtml.HTMLPhraseElement generatedLink = doc.getElementById("copybox") as mshtml.HTMLPhraseElement;
                if (generatedLink != null)
                {
                    mshtml.HTMLTextAreaElement text = generatedLink.children[0] as mshtml.HTMLTextAreaElement;
                    if (text != null)
                    {
                        m_sCurrentLinkbuck = text.value;
                        tbLinkbuck.Text = m_sCurrentLinkbuck;
                    }
                }
            }
        }

        
        private bool m_bGenerate = false;
        private void generateLink(string urlAdd)
        {
            var doc = (mshtml.HTMLDocument)wb.Document;

            if (doc != null)
            {
                mshtml.HTMLInputElement url = doc.getElementById("url") as mshtml.HTMLInputElement;

                mshtml.HTMLSelectElement selectContent = doc.getElementById("contentType") as mshtml.HTMLSelectElement;
               
                mshtml.HTMLInputElement generateBtn = doc.getElementById("generate") as mshtml.HTMLInputElement;

                if (url != null && selectContent != null && generateBtn != null)
                {
                    mshtml.HTMLOptionElement option1 = selectContent.options[1] as mshtml.HTMLOptionElement;
                    if (option1 != null)
                        option1.selected = true;

                    url.value = urlAdd;

                    generateBtn.click();
                    m_bGenerate = true;
                    waitvalue();
                }

            }
        }

        string m_sCurrentLink;
        private void OnLoadCompleted(object sender, NavigationEventArgs e)
        {
            if (m_bStartCreate == false)
            {
                onLogin();
                startThreadCreateLink();
            }
            else if (!m_bGenerate)
            {
                generateLink(m_sCurrentLink);
            }
            

        }

        private void loadLinkFromExcel(string sPath)
        {
            string filename = sPath;

            Microsoft.Office.Interop.Excel.Application appExcel;
            Workbook newWorkbook = null;
            _Worksheet objsheet = null;

            appExcel = new Microsoft.Office.Interop.Excel.Application();

            if (System.IO.File.Exists(filename))
            {
                // then go and load this into excel
                newWorkbook = appExcel.Workbooks.Open(filename, true, true);
                objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
            }
            else
            {

                System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
            }
            //Read data excel

            int nRow = objsheet.Rows.Count;

            if (nRow > 0)
                _listLinks.Clear();

            for (int i = 1; i < nRow; i++)
            {

                string cellName = String.Format("A{0}", i);
                string sName = String.Empty;
                try
                {
                    sName = objsheet.get_Range(cellName).get_Value().ToString();
                }
                catch
                {

                }

                if (sName != String.Empty)
                {
                    LinkBuckItem item = new LinkBuckItem();
                    item.RealLink = sName;
                    item.LinkBuck = "";
                    _listLinks.Add(item);
                }
                else
                {
                    break;
                }

            }

            //Release excel
            if (appExcel != null)
            {
                try
                {
                    newWorkbook.Close();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
                    appExcel = null;
                    objsheet = null;
                }
                catch (Exception ex)
                {
                    appExcel = null;

                }
                finally
                {
                    GC.Collect();
                }
            }


        }

        private void btnLoadFile_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".xls";
            dlg.Filter = "Excel Files (*.xls)|*.xls|Excel 2007 Files (*.xlsx)|*.xlsx";
            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();
            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                loadLinkFromExcel(dlg.FileName);
            }
        }
    }
}
